package cn.shequren.communityPeople.home.ui.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.view.ViewGroup;

import com.jz.community.basecomm.base.BaseMvpFragment;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by tlh on 2016/8/30 :)
 */
public class CommonViewPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragmentList;
    private List<CharSequence> titleList;
    FragmentManager fm;


    public CommonViewPagerAdapter(FragmentManager fm) {
        super(fm);
        this.fm = fm;
        this.fragmentList = new ArrayList<>();
        this.titleList = new ArrayList<>();
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

    @Override
    public int getCount() {
        return fragmentList.size();
    }

    public void addFragment(CharSequence title, Fragment fragment) {
        titleList.add(title);
        fragmentList.add(fragment);
    }

    public void addFragment(Fragment fragment) {
        addFragment("", fragment);
    }

    public void addFragment(Fragment fragment, int type) {
        fragmentList.add(fragment);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titleList.get(position);
    }
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        //拿到缓存的fragment，如果没有缓存的，就新建一个，新建发生在fragment的第一次初始化时
        Fragment f = (Fragment) super.instantiateItem(container, position);
        String fragmentTag = f.getTag();
        if (f != getItem(position)) {
            //如果是新建的fragment，f 就和getItem(position)是同一个fragment，否则进入下面
            FragmentTransaction ft = fm.beginTransaction();
            //移除旧的fragment
            ft.remove(f);
            //换成新的fragment
            f = getItem(position);
            //添加新fragment时必须用前面获得的tag
            ft.add(container.getId(), f, fragmentTag);
            ft.attach(f);
            ft.commitAllowingStateLoss();
        }
        return f;
    }
}
